package giit.computerbase.action;

import giit.computerbase.server.SearchServer;
import giit.computerbase.util.Application;
import giit.computerbase.util.DealWithCharcter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2018-11-28 Wednesday 19:41:43
 */
public class SearchServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));
        response.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));

        String name = request.getParameter("title");
        if (name != null) {
            name = URLDecoder.decode(name, "utf-8");
            name = DealWithCharcter.dealWith(name);
            SearchServer searchServer = new SearchServer();
            ArrayList<HashMap<String, Object>> result = searchServer.search(name);
            if (result.size() != 0) {
                request.getSession().setAttribute("search", result);
                response.sendRedirect("search.jsp");
            }else{
                response.sendRedirect("warn.jsp?state=panel-danger&title=" + URLEncoder.encode("搜索") + "&context=" + URLEncoder.encode("搜索失败，未找到相关记录") + "&preview=home.jsp");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
